# -*- coding:utf-8 -*-
"""
OKZ
http://www.okz.com/index/view

"""
import requests
import json
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_zx(url):
    try:
        text = json.loads(get_html_text(url))
        data = text['data']['list']
        dates = [date['newsTime'][:10] for date in data]
        return dates
    except:
        return None


def get_dates_kx(url):
    try:
        text = json.loads(get_html_text(url))
        data = text['data']['list']
        dates = [date['createDate'][:10] for date in data]
        return dates
    except:
        return None


def count_process_one():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        url = 'http://www.okz.com/news/newsList?pageNo={}&pageSize=10&currLanguage=zh-Hans'
        url = url.format(a)
        dates = get_dates_zx(url)
        if not dates:
            break
        print('----OKZ最新取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def count_process_two():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        url = 'http://www.okz.com/flash/flashList?pageNo={}&pageSize=20&currLanguage=zh-Hans'
        url = url.format(a)
        dates = get_dates_kx(url)
        if not dates:
            break
        print('----OKZ快讯取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = 'OKZ'
    t1 = count_process_one()
    t2 = count_process_two()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
